# Create your views here.
from django.contrib.auth import logout
from django.contrib.auth.views import password_change
from django.http import HttpResponseRedirect, Http404,HttpResponse
from django.shortcuts import render_to_response,render
from django.contrib.auth.decorators import login_required
from django import forms
from forms import SearchForm,ItemActionForm,ItemActionFormset,ActionForm,ChangePasswordForm,ItemForm
from inventory.models import Item,Location
from inventory.help import *

classes = set()

def logout_page(request):
	if request.user.is_authenticated():
		logout(request)
	return HttpResponseRedirect('/')
	
def main_page(request):
	return render(request, 'inventory/index.html')

@login_required
def changepw(request):
	if request.method == 'POST':
		form = ChangePasswordForm(request, request.POST)
		if form.is_valid():
			request.user.set_password(form.cleaned_data['new_pass'])
			request.user.save()
			return HttpResponseRedirect('/')
	else:
		form = ChangePasswordForm(request)
	return render(request,'inventory/changepw.html', {'form':form})
	
@login_required
def browse(request, page_id, per_page):
	obj = Item.objects.all()
	pg = int(page_id)
	per = int(per_page)
	start = (pg - 1) * per
	if start+per >= len(obj):
		end = len(obj)
	else:
		end = start + per
		
	
	total_pages = len(obj)/per
	if len(obj) % per != 0:
		total_pages += 1
	
	range_start = pg-3
	range_end = pg + 3
	
	if (range_start < 1):
		range_start = 1
		range_end = 7
	
	if (range_end > total_pages):
		range_end = total_pages+1
	
	page_list = range(range_start, range_end)
	
	return render(request, 'inventory/browse.html', {'items' : obj[start:end], 'page' : pg, 'per_page' : per, 'page_list' : page_list, 'last_page' : total_pages})
	
@login_required
def search(request):
	if request.method == 'POST':
		form = SearchForm(request.POST)
		if form.is_valid():
			cd = form.cleaned_data
			#find all items that match the query
			q = search_query(field = cd['field'], compare = cd['comparator'], value = cd['value'])
			if not q:
				return render(request, 'inventory/noresults.html')
				
			#initialize the 'action' formset which allows the user to delete/move inventory
			#each form represents an individual inventory item checkbox
			#the initial values for each form is set. a hidden field saves the Item id
			init_values = map(lambda x: {'item_id':x.id,'action':False}, q)
			items_formset = ItemActionFormset(initial = init_values,prefix='items')
	
			#another form is used to provide the actual action selector (delete, move, etc)
			action_form = ActionForm(prefix='action')
			return render(request, 'inventory/results.html', 
				{'items_formset' : items_formset, 'action_form' : action_form})
	else:
		form = SearchForm()
	return render(request,'inventory/search.html', {'form' : form })

@login_required
def action(request):
	if request.method == 'POST':
		items_formset = ItemActionFormset(request.POST, prefix='items')
		action_form = ActionForm(request.POST, prefix='action')
		if items_formset.is_valid() and action_form.is_valid():
			a_cd = action_form.cleaned_data
			items = []
			for form in items_formset:
				i_cd = form.cleaned_data
				if i_cd['action']:
					items.append(i_cd['item_id'])
			
			if a_cd['action'] == 'MOVE':
				if not a_cd['move_to']:
					return render(request, 'inventory/message.html', 
					{ 'header' : 'Error', 'msg' : 'You did not select a new location' })
				move_items_worker(items, a_cd['move_to'])
				return render(request, 'inventory/message.html', 
				{'header' : 'Success', 'msg' : 'The selected items have been moved'})
			else:
				delete_items_worker(items)
				return render(request, 'inventory/message.html', 
				{'header' : 'Success', 'msg' : 'The selected items have been deleted'})
		else:
			return render(request, 'inventory/message.html', 
			{'header': 'Error', 'msg' : 'Error: You submitted invalid form data'})
		
	return HttpResponseRedirect('/search')
	
@login_required
def update(request,action,obj_id=0): #action = ['add','edit']
	global classes
	if request.method == 'POST':
		if action=='edit':
			form = ItemForm(request.POST, instance=Item.objects.get(pk=obj_id))
		else:
			form = ItemForm(request.POST)
		if form.is_valid():
			cd = form.cleaned_data
			if(len(cd['classification'].strip()) > 1): #only add valid classes
				classes.add("'" + cd['classification'].strip() + "'")
			form.save()
			add_more = request.POST.get('add_more','f')
			if add_more == 't':
				return HttpResponseRedirect('/add')
			else:
				return render(request, 'inventory/message.html',
				{'header' : 'Success', 'msg' : 'The inventory was successfully updated'})
	else:
		if action=='edit':
			form = ItemForm(instance=Item.objects.get(pk=obj_id))
		else:
			form = ItemForm()

	if len(classes) == 0:
		for x in Item.objects.all():
			clas = x.classification.strip()
			if (len(clas) > 1): #only add valid classes
				classes.add("'%s'" % clas)
	
	return render(request, 'inventory/add.html',
	{'form':form, 'classes':classes, 'action':action})

